<template>
  <a-drawer v-model:visible="visible" title="角色分配" :ok-loading="loading" :width="500" @ok="onOk">
    <a-checkbox
      style="width: 45%"
      class="my-20"
      v-for="item in allRoles"
      :key="item.id"
      :value="item.id"
      :model-value="checkStatus(item.name)"
      @change="handleCheckStatus($event, item.name)"
      >{{ item.name }}</a-checkbox
    >
  </a-drawer>
</template>

<script setup>
import { allRoleList, adminUserRoles, adminUserRolesAdd } from '@/apis'
import { Message } from '@arco-design/web-vue'
const emit = defineEmits(['getTableData'])

const visible = ref(false)
const loading = ref(false)
const allRoles = ref([])
const adminUserRolesList = ref([])
const currentUserId = ref()

// 获取所有角色
const getGuardNameForPermissions = async () => {
  const res = await allRoleList()
  allRoles.value = res.data.data
}
getGuardNameForPermissions()

const addOrEdit = async (id) => {
  currentUserId.value = id
  const res = await adminUserRoles({ id })
  adminUserRolesList.value = res.data.data.map((item) => {
    return item.name
  })
  visible.value = true
}

const checkStatus = (name) => {
  const index = adminUserRolesList.value.findIndex((item) => {
    return item === name
  })
  return index > -1
}

const onOk = async () => {
  await adminUserRolesAdd({
    id: currentUserId.value,
    roles: adminUserRolesList.value
  })
  Message.success('操作成功')
  emit('getTableData')
  return true
}

const handleCheckStatus = (e, name) => {
  if (e) {
    adminUserRolesList.value.push(name)
  } else {
    adminUserRolesList.value.splice(
      adminUserRolesList.value.findIndex((item) => item === name),
      1
    )
  }
}

defineExpose({ addOrEdit })
</script>
